import logging
from datetime import timedelta

from advanced_json_encoding import decode
from pylons import config
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.decorators.rest import restrict

from sc.lib.base import BaseController, render

from sc.model.update import Updater

log = logging.getLogger(__name__)

update = Updater()

class UpdateController(BaseController):
    def __before__(self):
        body = decode(request.body, key_names_to_strings=True)

        given_password = body[0]
        expected_password = config['update_password']

        if len(expected_password) == 0 or given_password != expected_password:
            abort(401)

        self.data = body[1]

    @restrict('POST')
    def league(self):
        self.data.pop('alias')
        update.league(**self.data)

    @restrict('POST')
    def league_stage(self):
        update.league_stage(**self.data)

    @restrict('POST')
    def player(self):
        self.data.pop('aliases') 
        update.player(**self.data)

    @restrict('POST')
    def map(self):
        update.map(**self.data)

    @restrict('POST')
    def team(self):
        self.data.pop('aliases')
        update.team(**self.data)
    
    @restrict('POST')
    def proleague_match_id(self):
        update.proleague_match_id(**self.data)

    @restrict('POST')
    def proleague_match_data(self):
        update.proleague_match_data(**self.data)

    @restrict('POST')
    def game(self):
        update.game(**self.data)

    @restrict('POST')
    def commentary_set(self):
        update.commentary_set(**self.data)
